//
//  AppController.m
//  SneakyBrowser
//
//  This file is part of SneakyBrowser

//	This program is free software; you can redistribute it and/or
//	modify it under the terms of the GNU General Public License
//	as published by the Free Software Foundation; either version 2
//	of the License, or (at your option) any later version.

//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.

//	You should have received a copy of the GNU General Public License
//	along with this program; if not, write to the Free Software
//	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

//  Created by Krist Menina on 10/17/09.
//  Copyright 2009 Hello Wala Studios. All rights reserved.
//

#import <SystemConfiguration/SCNetwork.h>
#import <EDMessage/EDMessage.h> 
#import "AppController.h"
#import "GetSnapshots.h"
#import "MailOperation.h"



@interface AppController (Private)

- (void)setIsBusy:(BOOL)iBusy;
- (void)setTimer:(int)seconds;
- (void)startTimer;
- (void)stopTimer;
- (void)timerIncrement:(NSTimer *)aTimer;
- (void)refreshTable;
- (BOOL)isBusy;
- (BOOL)isConnected;
- (BOOL)useSmtpSettings;

@end

#define	TIMEOUT 30
#define CANCELTIMEOUT 200

@implementation AppController

- (id)init
{
	[super init];

	queue = [[NSOperationQueue alloc] init];
	tableRecord = [[NSMutableArray alloc] init];
	rootPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/temp"];
	[rootPath retain];
	
    return self;
}

- (void)dealloc
{
	[super dealloc];
}

- (BOOL)windowShouldClose:(id)sender
{
	NSLog(@" window should close");
	[NSApp terminate:sender];
	return YES;
}

- (void)awakeFromNib
{
	[tableView setTarget:self];
	[tableView setDoubleAction:@selector(doubleClickAction:)];
	[self loadSnapshotsStart:rootPath];
	[labelTimer setStringValue:@"0"];
	[labelTimer setFont:[NSFont fontWithName:@"Digital dream Narrow" size:22.0]];
	NSLog(@"smtp ok %d",[self useSmtpSettings]);
	
}


- (void)loadSnapshotsStart:(NSString *)path
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyThread_handleLoadedSnapshots:) name:LoadSnapshotsFinish object:nil];	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyThread_handleNoSnapshots:) name:NoSnapshotsFound object:nil];	

	[queue cancelAllOperations];
	
	// start the GetPathsOperation with the root path to start the search
	GetSnapshots* getSnaps = [[GetSnapshots alloc] initWithRootPath:path operationClass:nil queue:queue];
	
	[queue addOperation: getSnaps];	// this will start the "GetPathsOperation"
	[getSnaps release];	
	[progressBar setHidden:NO];
	[btnSend setEnabled:NO];
	[self setIsBusy:YES];
	
}

- (void)anyThread_handleLoadedSnapshots:(NSNotification *)note
{
	// update our table view on the main thread
	//[[NSNotificationCenter defaultCenter] removeObserver:self name:LoadSnapshotsFinish object:nil];	
	NSLog(@"handle snaps");
	[self performSelectorOnMainThread:@selector(updateTable:) withObject:note waitUntilDone:NO];
}

- (void)anyThread_handleNoSnapshots:(NSNotification *)note
{
	NSLog(@"no snapshots");
	[[NSNotificationCenter defaultCenter] removeObserver:self name:LoadSnapshotsFinish object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:NoSnapshotsFound object:nil];
	[self performSelectorOnMainThread:@selector(updateTable:) withObject:nil waitUntilDone:NO];
}

- (IBAction)sendMailStart:(id)sender
{
	NSLog(@"table rec count %d",[tableRecord count]);
	if([tableRecord count] <= 0){
		NSAlert *alert = [NSAlert alertWithMessageText: @"No Snapshots To Send"
										 defaultButton: @"OK"
									   alternateButton: nil
										   otherButton: nil
							 informativeTextWithFormat: @""];
		[alert beginSheetModalForWindow: [self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];		
	}else if(![self useSmtpSettings]){
		NSAlert *alert = [NSAlert alertWithMessageText: @"SMTP Settings Incomplete"
										 defaultButton: @"OK"
									   alternateButton: nil
										   otherButton: nil
							 informativeTextWithFormat: @"Please provide your mail settings in the Preferences panel."];
		[alert beginSheetModalForWindow: [self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];		
	}else if(![self isConnected]){
			NSAlert *alert = [NSAlert alertWithMessageText: @"Network unavailable"
											 defaultButton: @"OK"
										   alternateButton: nil
											   otherButton: nil
								 informativeTextWithFormat: @"Please check your network connection."];
			[alert beginSheetModalForWindow: [self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];	
	}else{
		// setup smtp credentials
		NSMutableDictionary *authInfo = [NSMutableDictionary dictionary];
		[authInfo setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"smtpUsername"] forKey:EDSMTPUserName];
		[authInfo setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"smtpPassword"] forKey:EDSMTPPassword];
		
		// setup email header
		NSMutableDictionary *headerFields = [NSMutableDictionary dictionary];
		[headerFields setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"emailFrom"] forKey:@"From"]; 
		[headerFields setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"emailAddress"] forKey:@"To"]; 	
		[headerFields setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"emailSubject"] forKey:@"Subject"];
		
		// setup attachments
		id item = NULL;
		NSEnumerator* iterator = [tableRecord objectEnumerator]; 
		NSMutableArray* attachmentList = [NSMutableArray array];
		NSMutableString* imgPath;
		while (item=[iterator nextObject]) 
		{
			imgPath = [NSString stringWithFormat:@"%@/%@",rootPath,[item valueForKey:@"name"]];
			NSData *imgData = [[NSData alloc] initWithContentsOfFile:imgPath];
			[attachmentList addObject:[EDObjectPair pairWithObjects:imgData:[imgPath lastPathComponent]]];
		}
		
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyThread_handleEmailSent:) name:EmailSentSuccess object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyThread_handleEmailSentFail:) name:EmailSentFail object:nil];

		[queue cancelAllOperations];
		
		int total = [self numberOfRowsInTableView:tableView];
		[labelTotal setStringValue:[NSString stringWithFormat:@"Sending %d snapshots",total]];
		// start the MailOperation with the root path to start the search
		[self startTimer];
		MailOperation* mailSnaps = [[MailOperation alloc] initWithRootPath:rootPath queue:queue attachList:attachmentList header:headerFields auth:authInfo];
		
		[queue addOperation: mailSnaps];	
		[mailSnaps release];	
		[btnSend setEnabled:NO];
		[progressBar setHidden:NO];
		[self setIsBusy:YES];

		NSLog(@" op count: %@",[queue operations]);
	}
}

-(void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
	NSLog(@"alert did end");
	[self refreshTable];
	//[self loadSnapshotsStart:rootPath];
}

- (void)anyThread_handleEmailSent:(NSNotification *)note
{
	NSLog(@"Email SentOK ");
	[[NSNotificationCenter defaultCenter] removeObserver:self name:EmailSentSuccess object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:EmailSentFail object:nil];
	[self performSelectorOnMainThread:@selector(deleteSnapshots) withObject:nil waitUntilDone:NO];
}

- (void)anyThread_handleEmailSentFail:(NSNotification *)note
{
	NSLog(@"Email Sent Failed");
	[[NSNotificationCenter defaultCenter] removeObserver:self name:EmailSentSuccess object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:EmailSentFail object:nil];
	[self performSelectorOnMainThread:@selector(alertSendFail) withObject:nil waitUntilDone:NO];
}

- (void)updateTable:(NSNotification *)note
{
	NSLog(@"update table %d",note != nil);
	NSLog(@"count %d",[tableRecord count]);
	if(note != nil){
		[tableRecord addObject:[note userInfo]];
		[tableView reloadData];	
	}
	[self refreshTable];
}

- (void)deleteSnapshots
{
	[self stopTimer];
	[progressBar setHidden:YES];
	[self setIsBusy:NO];
	//NSLog(@"rootPath: %@",rootPath);
	//NSLog(@"delete : %@",tableRecord);
	
	id item = NULL;
	NSEnumerator* iterator = [tableRecord objectEnumerator]; 	
	NSFileManager* fileManager = [NSFileManager defaultManager];
	NSMutableString* imgPath;
	int total = [self numberOfRowsInTableView:tableView];
	while (item=[iterator nextObject]) 
	{
		imgPath = [NSString stringWithFormat:@"%@/%@",rootPath,[item valueForKey:@"name"]];
		[fileManager removeItemAtPath:imgPath error:NULL];

		NSLog(@"delete --> %@",imgPath);
	}
	[tableRecord removeAllObjects];
	[tableView reloadData];
	[self refreshTable];
	[labelTotal setStringValue:[NSString stringWithFormat:@"%d snapshots sent in %d seconds",total,secs]];
	//[self loadSnapshotsStart:rootPath];

}

- (void)refreshTable
{
	NSLog(@"refresh table");
	int total = [self numberOfRowsInTableView:tableView];
	if(total){
		[labelTotal setStringValue:[NSString stringWithFormat:@"%d snapshots found",total]];
	}else{
		[labelTotal setStringValue:[NSString stringWithString:@"No snapshots found"]];
	}

	[btnSend setEnabled:YES];
	[progressBar setHidden:YES];
	[self setIsBusy:NO];
	[self stopTimer];

}

- (void)alertSendFail
{
	[self stopTimer];
	[self setIsBusy:NO];
	[progressBar setHidden:YES];
	[btnSend setEnabled:YES];
	NSAlert *alert = [NSAlert alertWithMessageText: @"Authentication Failed"
									 defaultButton: @"OK"
								   alternateButton: nil
									   otherButton: nil
						 informativeTextWithFormat: @"SMTP username and password is incorrect"];
	[alert beginSheetModalForWindow: [self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];	
}

- (void)alertTimeOut
{
	[self stopTimer];
	[self setIsBusy:NO];
	[progressBar setHidden:YES];
	[btnSend setEnabled:YES];
	NSAlert *alert = [NSAlert alertWithMessageText: @"Connection Timeout"
									 defaultButton: @"OK"
								   alternateButton: nil
									   otherButton: nil
						 informativeTextWithFormat: @"Network Connection timed out"];
	[alert beginSheetModalForWindow: [self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];	
	
}

- (float)getTimerSize
{
	return 25.0;
}

- (NSFont *)getTimerType
{
	NSFont* font = [NSFont fontWithName:@"Digital dream" size:25.0];
	return font;
}

- (BOOL)isBusy
{
	return isBusy;
}

- (void)setIsBusy:(BOOL)iBusy
{
	isBusy = iBusy;
}

- (void)startTimer
{
	//NSLog(@"timer %@",timer);
	secs = 0;
	to = 0;
	timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
											target:self 
											selector:@selector(timerIncrement:) 
											userInfo:0 
											repeats:YES]; 

	


}

- (void)stopTimer
{
	//NSLog(@"stop timer %@",timer);

	[timer invalidate];
	timer = nil;
		

}

- (void)setTimer:(int)seconds
{
	NSString* strSec = [NSString stringWithFormat:@"%d",seconds];
	[labelTimer setStringValue:strSec];
	[strSec release];
}

- (void)timerIncrement:(NSTimer *)aTimer
{
	//NSLog(@"timer %@",timer);
	NSLog(@"secs: %d %d",secs,[self isConnected]);
	secs++;
	if(![self isConnected]){
		to++;
		if(to >= TIMEOUT){
			[self alertTimeOut];
		}
	}else{
		to = 0;
		if(secs >= CANCELTIMEOUT){
			[self alertTimeOut];
		}
	}
	//[self setTimer:secs];
	[labelTimer setStringValue:[NSString stringWithFormat:@"%d",secs]];
}

- (BOOL)deleteAfterSending
{
	return [chkDeleteAfterSend state];
}

- (BOOL)isConnected
{
    Boolean success;
    BOOL okay;
    SCNetworkConnectionFlags status;
	
    success = SCNetworkCheckReachabilityByName("www.apple.com", 
											   &status);
	
    okay = success && (status & kSCNetworkFlagsReachable) && !(status & 
															   kSCNetworkFlagsConnectionRequired);

	
    return okay;
}

- (BOOL) useSmtpSettings
{
	return ([[NSUserDefaults standardUserDefaults] stringForKey:@"smtpURL"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"smtpPort"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"smtpUsername"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"smtpPassword"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"emailAddress"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"emailSubject"] != nil );
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
	return [tableRecord count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    id theRecord, theValue;
    
    theRecord = [tableRecord objectAtIndex:rowIndex];
    theValue = [theRecord objectForKey:[aTableColumn identifier]];
    
    return theValue;
}

- (void)sortWithDescriptor:(id)descriptor
{
	NSMutableArray *sorted = [[NSMutableArray alloc] initWithCapacity:1];
	[sorted addObjectsFromArray:[tableRecord sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]];
	[tableRecord removeAllObjects];
	[tableRecord addObjectsFromArray:sorted];
	NSLog(@"tblrec: %@",tableRecord);
	[tableView reloadData];
	[sorted release];
}

- (void)tableView:(NSTableView *)inTableView didClickTableColumn:(NSTableColumn *)tableColumn
{
	NSArray *allColumns=[inTableView tableColumns];
	NSInteger i;
	for (i=0; i<[inTableView numberOfColumns]; i++) 
	{
		if ([allColumns objectAtIndex:i]!=tableColumn)
		{
			[inTableView setIndicatorImage:nil inTableColumn:[allColumns objectAtIndex:i]];
		}
	}
	[inTableView setHighlightedTableColumn:tableColumn];
	
	if ([inTableView indicatorImageInTableColumn:tableColumn] != [NSImage imageNamed:@"NSAscendingSortIndicator"])
	{
		[inTableView setIndicatorImage:[NSImage imageNamed:@"NSAscendingSortIndicator"] inTableColumn:tableColumn];  
		NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:[tableColumn identifier] ascending:YES];
		[self sortWithDescriptor:sortDesc];
		[sortDesc release];
	}
	else
	{
		[inTableView setIndicatorImage:[NSImage imageNamed:@"NSDescendingSortIndicator"] inTableColumn:tableColumn];
		NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:[tableColumn identifier] ascending:NO];
		[self sortWithDescriptor:sortDesc];
		[sortDesc release];	
	}
}

- (void)doubleClickAction:(id)sender
{
	
	NSTableView *theTableView = (NSTableView *)sender;
	NSInteger selectedRow = [theTableView selectedRow];
	if (selectedRow != -1)
	{
		NSDictionary* objectDict = [tableRecord objectAtIndex: selectedRow];
		if (objectDict != nil)
		{
			//NSString *pathStr = [objectDict valueForKey: @"path"];
			NSString *completeURLStr = [rootPath stringByAppendingPathComponent:[objectDict valueForKey: @"name"]];
			//NSLog(@"tabledblclick%@",tableRecord);
			[[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:completeURLStr]];
		}
	}
}



@end
